﻿using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.Warehouse;
using NewRetail.Application.Components.Warehouse.Entity;
using NewRetail.Application.Core;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Dtos;

namespace NewRetail.Api.Controllers
{
    [NewRetailRoute("defective-bill")]
    public class DefectiveBillController : BaseController<DefectiveBill, DefectiveBillPagingDto>
    {
        private readonly IDefectiveBillService defectiveBillService;

        public DefectiveBillController(IDefectiveBillService defectiveBillService)
        {
            this.defectiveBillService = defectiveBillService;
        }

        protected override async Task<IQueryable<DefectiveBill>> FilterQueryPaging(DbContext db, IQueryable<DefectiveBill> query, DefectiveBillPagingDto dto)
        {
            if (!string.IsNullOrWhiteSpace(dto.receiptNo))
            {
                query = query.Where(x => x.receiptNo == dto.receiptNo || x.receiptNo.Contains(dto.receiptNo));
            }

            if (!string.IsNullOrWhiteSpace(dto.warehouseId))
            {
                query = query.Where(x => x.warehouseID == dto.warehouseId);
            }

            query = query.WhereIf(!string.IsNullOrWhiteSpace(dto.supplierId), x => x.supplierID == dto.supplierId);
            if (dto.isAuditing != null)
            {
                query = query.Where(x => x.isAuditing == dto.isAuditing.Value);
            }

            await Task.CompletedTask;
            return query;
        }

        public override async Task<ResponseEntity<PagedResultDto<DefectiveBill>>> QueryPaging([FromBody] DefectiveBillPagingDto dto)
        {
            var res = await base.QueryPaging(dto);

            if (res.Data?.Items?.Any() ?? false)
            {
                res.Data.Items = await this.defectiveBillService.AttachGoodsInfo(res.Data.Items.ToArray());
                res.Data.Items = await this.defectiveBillService.AttachSupplier(res.Data.Items.ToArray());
                res.Data.Items = await this.defectiveBillService.AttachWarehouse(res.Data.Items.ToArray());
            }

            return res;
        }

        [HttpPost("save-multiple")]
        public async Task<ResponseEntity<DefectiveBill[]>> SaveMultiple([FromBody] ReceiptNoItemsDto<DefectiveBill> data)
        {
            var res = await this.Repo.SaveReceiptItems(this.HttpContext.RequestServices, data, "CP");
            return new ResponseEntity<DefectiveBill[]>().SetData(res.Items);
        }


        [HttpPost("query-by-receipt-no")]
        public async Task<ResponseEntity<DefectiveBill[]>> QueryByReceiptNo([FromBody] ReceiptNoDto dto)
        {
            dto.Should().NotBeNull();
            dto.receiptNo.Should().NotBeNullOrEmpty();
            var query = this.SingleStoreService.ApplyToQueryable(this.Repo);
            var data = await query.Where(x => x.receiptNo == dto.receiptNo).ToArrayAsync();

            data = await this.defectiveBillService.AttachGoodsInfo(data);
            data = await this.defectiveBillService.AttachSupplier(data);
            data = await this.defectiveBillService.AttachWarehouse(data);
            data = data.OrderBy(x => x.GoodsInfo?.No).ToArray();
            return new ResponseEntity<DefectiveBill[]>().SetData(data);
        }

        /// <summary>
        /// 每条次品单只显示一条记录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("query-paging-distinct")]
        public async Task<ResponseEntity<PagedResultDto<DefectiveBill>>> QueryPagingDistinct([FromBody] DefectiveBillPagingDto dto)
        {
            var query = await base.GetQueryPagingData(dto);
            var data = new PagedResultDto<DefectiveBill>();
            query = await this.OrderQueryPaging(query, dto);

            query = query.WhereIf(dto.startTime != null, x => x.receiptDate >= dto.startTime.Value);
            query = query.WhereIf(dto.endTime != null, x => x.receiptDate < dto.endTime.Value);

            var list = query.ToList().GroupBy(g => new { g.receiptDate, g.receiptNo, g.warehouseID })
                .Select(x => new DefectiveBill
                {
                    receiptDate = x.Key.receiptDate,
                    receiptNo = x.Key.receiptNo,
                    warehouseID = x.Key.warehouseID,
                    supplierID = x.Select(a => a.supplierID).FirstOrDefault(),
                    quantity = x.Sum(s => s.quantity),
                    price = x.Sum(s => s.price * s.quantity),//由于字段中没有对应金额参数，因此这边借用price字段供前端显示金额列
                    isAuditing = x.Select(a => a.isAuditing).FirstOrDefault(),
                    operateTime = x.Select(a => a.operateTime).FirstOrDefault()
                }).ToList();

            //logger.LogInformation(">>>>>>>>>>>>>>>>>>Count:" + query.Count());
            //去重(同一批次的入库单单号相同)
            //var list = query.ToList().Distinct(new InOutWarehousingComparer()).ToList();
            //query = query.GroupBy(io => new { io.receiptDate, io.receiptNo, io.Id, io.warehouseID, io.supplierID }).Select(io => io.First());

            data.TotalCount = list.Count();
            //logger.LogInformation(">>>>>>>>>>>>>>>>>>TotalCount：" + data.TotalCount);
            list = list.Skip((dto.Page - 1) * dto.PageSize).Take(dto.PageSize).ToList();
            //logger.LogInformation(">>>>>>>>>>>>>>>>>>5");
            data.Items = list.ToArray();
            ResponseEntity<PagedResultDto<DefectiveBill>> res = new ResponseEntity<PagedResultDto<DefectiveBill>>().SetData(data);

            if (res.Data?.Items?.Any() ?? false)
            {
                //res.Data.Items = await this.defectiveBillService.AttachSupplier(res.Data.Items.ToArray());
                res.Data.Items = await this.defectiveBillService.AttachWarehouse(res.Data.Items.ToArray());
            }

            return res;
        }

        #region add by cl 20221222
        /// <summary>
        /// 整单删除得根据receiptNo找到id
        /// </summary>
        /// <param name="ids">receiptNo数组</param>
        /// <returns></returns>
        protected override async Task<string[]> BeforeDelete(string[] ids)
        {
            string[] delIds = null;

            if (ids.Length > 0)
            {
                var query = this.SingleStoreService.ApplyToQueryable(this.Repo);
                //找出未审核的单据
                delIds = await query.Where(g => ids.Contains(g.receiptNo) && g.isAuditing == false).Select(g => g.Id).Distinct().ToArrayAsync();
            }
            if (delIds.Length == 0)
            {
                throw new UserFriendlyException("没有要删除的记录！");
            }

            return delIds;
        }
        #endregion
    }
}
